package com.neethi.webapp.action;

import java.util.List;

import com.neethi.model.PracticeArea;
import com.neethi.service.PracticeAreaManager;
import com.opensymphony.xwork2.Preparable;

public class PracticeAreaAction extends BaseAction implements Preparable {
    private PracticeAreaManager practiceAreaManager;
    private List practiceAreas;
    private PracticeArea practiceArea;
    private Long  sid;

    public void setPracticeAreaManager(PracticeAreaManager practiceAreaManager) {
        this.practiceAreaManager = practiceAreaManager;
    }

    public List getPracticeAreas() {
        return practiceAreas;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String practiceAreaId = getRequest().getParameter("practiceArea.sid");
            if (practiceAreaId != null && !practiceAreaId.equals("")) {
                practiceArea = practiceAreaManager.get(new Long(practiceAreaId));
            }
        }
    }

    public String list() {
        practiceAreas = practiceAreaManager.getAll();
        return SUCCESS;
    }

    public void setSid(Long  sid) {
        this. sid =  sid;
    }

    public PracticeArea getPracticeArea() {
        return practiceArea;
    }

    public void setPracticeArea(PracticeArea practiceArea) {
        this.practiceArea = practiceArea;
    }

    public String delete() {
        practiceAreaManager.remove(practiceArea.getSid());
        saveMessage(getText("practiceArea.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (sid != null) {
            practiceArea = practiceAreaManager.get(sid);
        } else {
            practiceArea = new PracticeArea();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (practiceArea.getSid() == null);

        practiceAreaManager.save(practiceArea);

        String key = (isNew) ? "practiceArea.added" : "practiceArea.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}